package humrum.weguide.net;

import humrum.weguide.R;

import java.lang.ref.SoftReference;
import java.util.HashMap;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;

public class ImageManage {

	private static HashMap<String, SoftReference<Drawable>> cache;
	private static Drawable icon_wi;

	public ImageManage(Context context) {
		cache = new HashMap<String, SoftReference<Drawable>>();
		icon_wi = new BitmapDrawable(BitmapFactory.decodeResource(
				context.getResources(), R.drawable.icon));
	}

	public Drawable loadDrawable(final String imageUrl,
			final ImageCallback imageCallback) {
		if (imageUrl.equals("null")) {
			return icon_wi;
		}
		if (cache.containsKey(imageUrl)) {
			SoftReference<Drawable> softReference = cache.get(imageUrl);
			Drawable drawable = softReference.get();
			if (drawable != null) {
				return drawable;
			}
		}
		final Handler handler = new Handler() {
			@Override
			public void handleMessage(Message message) {
				imageCallback.imageLoaded((Drawable) message.obj, imageUrl);
			}
		};
		new Thread() {
			@Override
			public void run() {
				Drawable drawable = loadImageFromUrl(imageUrl);
				cache.put(imageUrl, new SoftReference<Drawable>(drawable));
				Message message = handler.obtainMessage(0, drawable);
				handler.sendMessage(message);
			}
		}.start();
		return null;
	}

	public static Drawable loadImageFromUrl(String url) {
		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpGet request = new HttpGet(url);
		try {
			HttpResponse response = httpClient.execute(request);
			return Drawable.createFromStream(response.getEntity().getContent(),
					"src");
		} catch (Exception e) {
			return null;
		}
	}

	public static SoftReference<Drawable> getDrawableFromCache(String tag) {
		return cache.get(tag);
	}

	public interface ImageCallback {
		public void imageLoaded(Drawable imageDrawable, String imageUrl);
	}
}
